package com.xnyzc.lhy.common.util.sign;

import com.xnyzc.lhy.common.constant.InvoiceAaUrlConstant;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 发票请求验签(Aa)
 *
 * @author 刘举
 */
@Slf4j
@Component
public class InvoiceAaSign {

    /**
     * 请求参数加签
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T> String getSign(T t) {
        Map<String, Object> resMap = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String str1, String str2) {
                return str1.compareTo(str2);
            }
        });

        try {
            Map<String, Object> map = BeanUtils.describe(t);
            map.remove("class");
            resMap.putAll(map);
        } catch (Exception e) {
            log.info("发票请求验签异常，错误信息：{}", e);
        }
        StringBuilder signParam = new StringBuilder();
        signParam.append(InvoiceAaUrlConstant.VENDOR_KEY);
        for (Object key : resMap.keySet()) {
            if (key.equals("sign")) {
                continue;
            }
            if(CheckUtil.objIsNotEmpty(resMap.get(key))){
                signParam.append(key);
                signParam.append(resMap.get(key));
            }
        }
        signParam.append(InvoiceAaUrlConstant.VENDOR_SECRET);
        // 进行md5加密
        String signStr = MD5Util.MD5(String.valueOf(signParam)).toUpperCase();

        return signStr;
    }


}
